<template>
  <div>
    <canvas id="canvas" width="800" height="600"></canvas>
  </div>
</template>

<script>
import { onMounted } from 'vue'
import {
  Canvas,
  Rect,
  FabricText,
  Group,
  Line,
  FabricImage,
  loadSVGFromURL,
  util,
} from 'fabric'
export default {
  name: 'TopologyEditor',
  setup() {
    onMounted(() => {
      const canvas = new Canvas('canvas')

      // 创建节点
      const createNode = (left,top,label) => {
        const rect = new Rect({
          left,
          top,
          fill: 'lightblue',
          width: 100,
          height: 50,
          rx: 10,
          ry: 10,
          hasControls: false,
          hasBorders: false,
        })

        const text = new FabricText(label,{
          left: left + 10,
          top: top + 15,
          fontSize: 16,
          fill: 'black',
        })

        const group = new Group([rect,text],{
          left,
          top,
          hasControls: false,
          hasBorders: false,
        })

        group.on('mousedown',(e) => {
          const pointer = canvas.getPointer(e.e)
          const line = new Line([pointer.x,pointer.y,pointer.x,pointer.y],{
            stroke: 'black',
            strokeWidth: 2,
            selectable: false,
          })
          canvas.add(line)

          canvas.on('mouse:move',(e) => {
            const pointer = canvas.getPointer(e.e)
            line.set({ x2: pointer.x,y2: pointer.y })
            canvas.renderAll()
          })

          canvas.on('mouse:up',() => {
            canvas.off('mouse:move')
            canvas.off('mouse:up')
          })
        })

        return group
      }

      // 添加节点到画布
      const node1 = createNode(100,100,'Node 1')
      const node2 = createNode(300,300,'Node 2')
      canvas.add(node1)
      canvas.add(node2)
      // 加载图片并添加到画布
      loadSVGFromURL('/vite.svg').then((svg) => {
        const obj = util.groupSVGElements(svg.objects)
        obj.clone().then((clone) => {
          canvas.add(clone)
        })
      })
    })
  },
}
</script>

<style scoped>
#canvas {
  border: 1px solid #000;
}
</style>